import asyncio
from pymodbus.client import ModbusTcpClient
from pymodbus.exceptions import ModbusException

# 服务器IP和端口
HOST = "127.0.0.1"  # Modbus TCP 服务器地址
PORT = 502          # Modbus TCP 端口
UNIT_ID = 1         # Modbus从站设备地址

async def run_client():
    # 创建 Modbus TCP 客户端
    client = ModbusTcpClient(HOST, port=PORT, timeout=3)

    try:
        # 连接到 Modbus 服务器
        if client.connect():
            print(f"Connected to Modbus TCP server at {HOST}:{PORT}")


            # 读取离散输入寄存器
            address = 0  # 寄存器地址
            count = 8    # 读取数量
            try:
                # 从地址 0 开始读取 10 个离散输入寄存器
                response = client.read_discrete_inputs(address=address, count=count, slave=UNIT_ID)
                if response.isError():
                    print(f"Error reading coil registers: {response}")
                else:
                    print(f"离散输入状态:", response.bits)
            except ModbusException as e:
                print("Exception while reading holding registers:", e)
            # 读取线圈寄存器
            address = 0  # 寄存器地址
            count = 8    # 读取数量
            try:
                response = client.read_coils(address=address, count=count, slave=UNIT_ID)
                if response.isError():
                    print(f"Error reading coil registers: {response}")
                else:
                    print(f"线圈寄存器状态:", response.bits)
            except ModbusException as e:
                print("Exception while reading holding registers:", e)

            # 读取保持寄存器
            address = 0  # 寄存器地址
            count = 10    # 读取数量
            try:
                response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
                if response.isError():
                    print(f"Error reading holding registers: {response}")
                else:
                    print(f"保持寄存器:", response.registers)
            except ModbusException as e:
                print("Exception while reading holding registers:", e)

            # 读取输入寄存器
            address = 0  # 寄存器地址
            count = 10    # 读取数量
            try:
                response = client.read_input_registers(address=address, count=count, slave=UNIT_ID)
                if response.isError():
                    print(f"Error reading holding registers: {response}")
                else:
                    print(f"输入寄存器 :", response.registers)
            except ModbusException as e:
                print("Exception while reading holding registers:", e)

            # # 写入保持寄存器
            # new_value = 0x5678  # 新的寄存器值
            # try:
            #     response = client.write_register(address=address, value=new_value, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error writing holding register: {response}")
            #     else:
            #         print(f"Holding register at address {address} set to {new_value}")
            # except ModbusException as e:
            #     print("Exception while writing holding register:", e)

            # # 再次读取保持寄存器，验证写入是否成功
            # try:
            #     response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error reading holding registers after write: {response}")
            #     else:
            #         print(f"Holding register value (address {address}) after write:", response.registers[0])
            # except ModbusException as e:
            #     print("Exception while re-reading holding registers:", e)

        else:
            print("Failed to connect to Modbus TCP server")

    except Exception as e:
        print("General error:", e)

    finally:
        # 关闭连接
        client.close()
        print("Modbus connection closed")

if __name__ == "__main__":
    asyncio.run(run_client())
